package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciei.dpagm.common.service.BaseService;

import com.ciei.dpagm.entity.Region;

import com.ciei.dpagm.entity.Users;
import com.ciei.dpagm.mapper.RegionMapper;

import com.ciei.dpagm.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RegionService extends BaseService<RegionMapper,Region> {
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UsersService usersService;




    public JSONObject add(Region region) {
        JSONObject json;

        if(save(region)==true){
            json= JsonUtil.getSuccess("OK");
            json.put(APP.DATA,region);
        }else{
            json=JsonUtil.getFail("增加失败");
        }
        return json;

    }

    public List<Region> queryAllRegion()
    {
        return findByProperty("isDelete",0);
    }

    public JSONObject loadTreeVue(Integer companyId){
       // List<Region> lists = findByProperties(new String[]{"isDelete","companyId"}, new Object[]{"0", companyId});
        List<Region> lists = findByProperties(new String[]{"isDelete"}, new Object[]{"0"});
        JSONObject json = new JSONObject();
        Map<String, Object> oneMap = new HashMap<String, Object>();
        oneMap.put("id",companyId);
        oneMap.put("label",companyService.getCompanyName(companyId));
        List<TreeNode> treeNodes= TreeUtils.buildTree(lists
                ,Region::getRegionId
                , region -> region.getParentRegionId()
                , Region::getRegionName);
        oneMap.put("children",treeNodes);
        oneMap.put("company",true);
        json.fluentPut(APP.DATA, oneMap);
        return json;
    }
    /**
     * 保存试验区域信息
     * @param jsonObject
     * @return
     */
    public JSONObject addOrUpdate(JSONObject jsonObject,String type) {
        String regionName = jsonObject.getString("regionName");
        JSONObject json = new JSONObject();
        String[] propertyNames = {"regionName","isDelete","parentRegionId"};
        Object[] values;
        List<Region> list=new ArrayList<>();
        if("add".equals(type)){
            if(jsonObject.getInteger("regionId")==null){
                values = new Object[]{regionName, 0, 0};
            }else{
                values = new Object[]{regionName, 0, jsonObject.getInteger("regionId")};

            }
            list=findByProperties(propertyNames, values);
            if(list.size()>0){
                json = JsonUtil.getFail("该试验区域名字已经存在,添加失败！");
            }
        }else{
            //更新的时候判断是否重复不包括自己
            Region region = findById(jsonObject.getInteger("regionId"));
            values = new Object[]{regionName, 0, region.getParentRegionId()};
            if(region!=null){
                list=findByPropertiesNotSelf(propertyNames,values,jsonObject.getInteger("regionId"));
            }
            if(list.size()>0){
                json = JsonUtil.getFail("该试验区域名字已经存在,更新失败！");
            }
        }
        if(list.size()==0 ) {
            Region region = new Region();
            region.setIsDelete(0);
            region.setRegionDescribe(jsonObject.getString("regionDescribe"));
            region.setRegionName(jsonObject.getString("regionName"));
            if(jsonObject.getJSONObject("user")!=null){
                if(jsonObject.getJSONObject("user").getInteger("id")!=null){
                    region.setResponsibleUserId(jsonObject.getJSONObject("user").getInteger("id"));
                }
            }
            if("add".equals(type)){
                //添加跟更新传的键都为regionId，如果是添加时，regionId应该理解为父节点(添加当前节点的子节点)，更新理解为当前节点
                if(jsonObject.getInteger("regionId")==null){
                    //如果是null,说明父节点为公司，添加公司的一级试验区域子节点，父节点应该为0
                    region.setParentRegionId(0);
                }else{
                    region.setParentRegionId(jsonObject.getInteger("regionId"));
                }
                save(region);
                json = JsonUtil.getSuccess("添加成功");
                json.put(APP.DATA,region.getRegionId());
            }else{
                if(jsonObject.getInteger("regionId")==null){
                    json = JsonUtil.getFail("regionId不能为空，更新失败");
                }else{
                    region.setRegionId(jsonObject.getInteger("regionId"));
                    updateById(region);
                    json = JsonUtil.getSuccess("更新成功");
                }
            }
        }
        return json;
    }
    /**
     * 多条件等值查询并且忽略自己
     *
     * @param propertyNames 属性名数组
     * @param values        属性值数组
     * @return 满足条件的所有记录
     */
    public List<Region> findByPropertiesNotSelf(String[] propertyNames, Object[] values,Integer regionId) {

        QueryWrapper<Region> wrapper = new QueryWrapper<>();
        propertyNames = ConvertUtil.humpToLines(propertyNames);
        if (propertyNames != null) {
            for (int i = 0; i < propertyNames.length; i++) {
                if (values[i] != null) {
                    wrapper.eq(propertyNames[i], values[i]);
                } else {
                    wrapper.isNull(propertyNames[i]);
                }
            }
        }
        if(regionId!=null){
            wrapper.notIn("region_id",regionId);
        }
        return list(wrapper);
    }
    public JSONObject deleteVue(JSONObject jsonObject){
        JSONObject json;
        List<Region> list = new ArrayList<>();
        List<Region> all = null;
        if(jsonObject.getInteger("regionId")!=null){
            Set<Integer> sonIdSet = new HashSet<>();
            Integer regionId= jsonObject.getInteger("regionId");
            all = findByProperty("isDelete",0);
            loadChildrenRegionIds(all, regionId, sonIdSet);
            list = findListByIds(sonIdSet);
            if(list != null && list.size()>0) {
                removeByIds(list.stream().map(Region::getRegionId).collect(Collectors.toList()));
            }
            json = JsonUtil.getSuccess("删除成功!");
        }else{
            json = JsonUtil.getFail("删除失败,请选择要删除的数据");
        }
        return json;
    }
    /**
     * 根据区域ID获取所有下级区域的ID
     * @param allRegions	区域范围全集
     * @param regionId		区域ID
     * @param idSet				筛选出的区域ID，包含区域ID本身及其所有下级区域的ID
     */
    public void loadChildrenRegionIds(List<Region> allRegions, Integer regionId, Set<Integer> idSet) {
        Queue<Integer> RegionIdQueue = new LinkedList<>();
        RegionIdQueue.add(regionId);
        while (!RegionIdQueue.isEmpty()) {
            Integer id = RegionIdQueue.poll();
            idSet.add(id);
            List<Integer> childrenIds = allRegions.stream().filter(d -> id.equals(d.getParentRegionId()))
                    .map(Region::getRegionId).filter(Objects::nonNull).collect(Collectors.toList());
            RegionIdQueue.addAll(childrenIds);
        }
    }
    public JSONObject loadRegionDataVue(JSONObject jsonObject){
        JSONObject json = new JSONObject();
        if(jsonObject.getInteger("regionId")!=null){
            Map<String,Object> jsonData = new HashMap<>();
            List<Region> regions = findByProperties(new String[]{"regionId","isDelete"}, new Integer[]{jsonObject.getInteger("regionId"),0});
            if(regions.size()>0){
                Region region = regions.get(0);
                jsonData.put("regionId",region.getRegionId());
                jsonData.put("regionName",region.getRegionName());
                jsonData.put("regionDescribe",region.getRegionDescribe());
                Map<String,Object> userMap = new HashMap<>();
                if(region.getResponsibleUserId()!=null){
                    userMap.put("id",region.getResponsibleUserId());
                    Users user = usersService.findById(region.getResponsibleUserId());
                    userMap.put("value",user.getUserName());
                    jsonData.put("mobileTel",user.getMobileTel());

                }else{
                    userMap.put("id",null);
                    userMap.put("value","");
                }
                jsonData.put("user",userMap);
                json.put(APP.DATA,jsonData);
            }
        }
        return json;
    }

    /**
     * 获取没有子集的区域
     */
    public JSONObject getNoChildNodesRegionList(){
        //查找区域
        JSONArray regionArray = new JSONArray();
        QueryWrapper<Region> wrapper = new QueryWrapper<>();
        wrapper.lambda().ne(Region::getParentRegionId,0);
        List<Region> listParent = list(wrapper);
        //有子集的
        List<Integer> parentList = listParent.stream().filter(w->w.getParentRegionId() != null).map(Region::getParentRegionId).collect(Collectors.toList());
        List<Region> list = null;
        if (parentList != null && parentList.size()>0){
            QueryWrapper<Region> noChildNodesWrapper = new QueryWrapper<>();
            noChildNodesWrapper.lambda().notIn(Region::getRegionId,parentList);
            //无子集的
            list = list(noChildNodesWrapper);
        }
        if (list != null && list.size()>0){
            for(Region region:list){
                JSONObject regionData = new JSONObject();
                regionData.put("regionId",region.getRegionId());
                regionData.put("regionName",region.getRegionName());
                regionArray.add(regionData);
            }
        }
        return JsonUtil.getSuccess("").fluentPut(APP.DATA, regionArray);
    }

    /**获取树形区域名称  例如（东区 2栋 一楼 305）
     * @param region
     * @param regionList
     * @return
     */
    public String getTreeRegionName(Region region,List<Region> regionList) {
        StringBuilder treeName = new StringBuilder();
        Integer parentRegionId = region.getParentRegionId();
        Region parentRegion = regionList.stream().filter(w -> w.getRegionId().equals(parentRegionId)).findFirst().orElse(null);
        while (parentRegion != null){
            treeName.insert(0,parentRegion.getRegionName()+" ");
            Region finalParentRegion = parentRegion;
            parentRegion = regionList.stream().filter(w -> w.getRegionId().equals(finalParentRegion.getParentRegionId())).findFirst().orElse(null);
        }
        treeName = treeName.append(region.getRegionName());
        return treeName.toString();
    }

    /**
     * 查找区域
     * @return
     */
    public JSONObject findRegion() {
        JSONObject json = JsonUtil.getSuccess("");
        JSONArray jarr = new JSONArray();
        QueryWrapper<Region> wrapper = new QueryWrapper<>();
        wrapper.lambda().ne(Region::getParentRegionId,0);
        wrapper.lambda().eq(Region::getIsDelete,0);
        List<Region> listParent = list(wrapper);
        //有子集的
        List<Integer> parentList = listParent.stream().filter(w->w.getParentRegionId() != null).map(Region::getParentRegionId).collect(Collectors.toList());
        List<Region> list = null;
        if (parentList != null && parentList.size()>0){
            QueryWrapper<Region> wrapper1 = new QueryWrapper<>();
            wrapper1.lambda().eq(Region::getIsDelete,0);
            wrapper1.lambda().notIn(Region::getRegionId,parentList);
            //无子集的
            list = list(wrapper1);
        }
        if (list != null && list.size()>0){
            for(Region region:list){
                HashMap<String, Object> map = new HashMap<>(16);
                map.put("text",region.getRegionName());
                map.put("value",region.getRegionId());
                jarr.add(map);
            }
        }
        json.put(APP.DATA,jarr);
        return json;
    }

    
}
